package com.xiaomage.ipcdemo

import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.net.Uri
import android.util.Log

class ContactContentProvider:ContentProvider() {
    companion object {
        private const val TAG="联系人内容提供者"
        private const  val AUTHORITY="com.xiaomage.contact"
        private const val CONTACT_NAME_CODE=0
        const val CONTACT_URI="content://$AUTHORITY/${ContactOpenHelper.CONTACT_TABLE_NAME}"
    }
    private var uriMatcher:UriMatcher?=null
    private var sqLiteDatabase:SQLiteDatabase?=null
    override fun onCreate(): Boolean {
        Log.e(TAG,"ContactContentProvider--onCreate--进程ID：${android.os.Process.myPid()}")
        uriMatcher= UriMatcher(UriMatcher.NO_MATCH)
        uriMatcher?.addURI(AUTHORITY,ContactOpenHelper.CONTACT_TABLE_NAME, CONTACT_NAME_CODE)
        sqLiteDatabase=ContactOpenHelper(context).writableDatabase
        return false
    }
    private fun getTableName(uri: Uri?):String{
        var tableName=""
        when(uriMatcher?.match(uri)){
            CONTACT_NAME_CODE->{
                tableName=ContactOpenHelper.CONTACT_TABLE_NAME
            }
        }
        return tableName
    }
    override fun query(uri: Uri?, projection: Array<out String>?, selection: String?,
                       selectionArgs: Array<out String>?, sortOrder: String?): Cursor? {
        val tableName=getTableName(uri)
        val cursor=sqLiteDatabase?.query(tableName,projection,
                selection,selectionArgs,sortOrder,null,null)
        return cursor
    }
    override fun insert(uri: Uri?, values: ContentValues?): Uri?{
        val tableName=getTableName(uri)
        sqLiteDatabase?.insert(tableName,null,values)
        context.contentResolver.notifyChange(uri,null)
        return null
    }

    override fun delete(uri: Uri?, selection: String?, selectionArgs: Array<out String>?): Int {
        val tableName=getTableName(uri)
        val count=sqLiteDatabase?.delete(tableName,selection,selectionArgs)
        if(count!=null && count>0){
            context.contentResolver.notifyChange(uri,null)
        }
        return 0
    }

    override fun update(uri: Uri?, values: ContentValues?, selection: String?,
                        selectionArgs: Array<out String>?): Int {
        return 0
    }


    override fun getType(uri: Uri?): String {
        return "联系人类型"
    }
}